package com.novelot.demo

import com.squareup.javapoet.*
import java.io.IOException
import javax.annotation.processing.Filer
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.element.VariableElement
import javax.lang.model.util.Elements

class ClassCreatorProxy(elementUtils: Elements, private val mTypeElement: TypeElement) {
    private val mPackageElement = elementUtils.getPackageOf(mTypeElement)
    private val mPackageName = mTypeElement.qualifiedName.toString()
    private val mBindingClassName = "${mTypeElement.simpleName.toString()}_ViewBinding"
    private val mVariableElementMap = mutableMapOf<Int, VariableElement>()


    fun putElement(id: Int, element: VariableElement) {
        mVariableElementMap[id] = element
    }

//    fun getProxyClassFullName(): String = "$mPackageName.$mBindingClassName"

//    fun getTypeElement(): Element = mTypeElement

    private fun generateJavaCode(): TypeSpec {
        return TypeSpec.classBuilder(mBindingClassName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(generateMethod())
            .build()
    }

    private fun generateMethod(): MethodSpec {
        val className = ClassName.bestGuess(mTypeElement.qualifiedName.toString())
        val methodBuilder = MethodSpec.methodBuilder("bind")
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.VOID)
            .addParameter(className, "host")
        mVariableElementMap.forEach { (id, element) ->
            val name = element.simpleName.toString()
            val type = element.asType().toString()

            methodBuilder.addCode(
                """
                host.$name = ($type)(((android.app.Activity)host).findViewById($id));
            """.trimIndent()
            )
        }

        return methodBuilder.build()
    }

    fun createJavaFile(filer: Filer) {
        //write1(filer)
        val javaFile = JavaFile.builder(mPackageName, generateJavaCode()).build()
        try {
            javaFile.writeTo(filer)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

//    private fun write1(filer: Filer) {
//        try {
//            val javaFileObject = filer.createSourceFile(getProxyClassFullName(), getTypeElement())
//            val writer = javaFileObject.openWriter()
//            writer.write(generateJavaCode())
//            writer.flush()
//            writer.close()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//    }
}